package com.itheima.service.store.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.domain.store.Course;
import com.itheima.dao.store.CourseMapper;
import com.itheima.service.store.CourseService;
import com.itheima.utils.MysqlUtils;
import org.apache.ibatis.session.SqlSession;

import java.util.List;
import java.util.UUID;
/**
 *  course的增删改查
 *  2021/10/16
 *  create by guowenliang
 */
public class CourseServiceImpl implements CourseService {
    @Override
    public PageInfo findByPage(String pageNum) {
        // 分页查询
        int page = pageNum==null||pageNum=="" ? 1 : Integer.parseInt(pageNum);
        PageHelper.startPage(page,5);
        SqlSession sqlSession = MysqlUtils.getSqlSession();
        CourseMapper courseMapper = sqlSession.getMapper(CourseMapper.class);
        List<Course> courseList = courseMapper.findAll();
        PageInfo pageInfo = new PageInfo(courseList);
        sqlSession.close();
        return pageInfo;
    }

    @Override
    public void addCourse(Course course, String username) {
        SqlSession sqlSession = MysqlUtils.getSqlSession();
        CourseMapper courseMapper = sqlSession.getMapper(CourseMapper.class);
        // 添加course的成员变量
        course.setId(UUID.randomUUID().toString());
        course.setCreateBy(username);
        course.setUpdateBy(username);
        courseMapper.addCourse(course);
        sqlSession.close();
    }

    @Override
    public void updateCourse(Course course) {
        SqlSession sqlSession = MysqlUtils.getSqlSession();
        CourseMapper courseMapper = sqlSession.getMapper(CourseMapper.class);
        courseMapper.updateCourse(course);
        sqlSession.close();
    }

    @Override
    public void deleteCourse(String id) {
        SqlSession sqlSession = MysqlUtils.getSqlSession();
        CourseMapper courseMapper = sqlSession.getMapper(CourseMapper.class);
        courseMapper.deleteCourse(id);
        sqlSession.close();
    }

    @Override
    public Course findCourseById(String id) {
        SqlSession sqlSession = MysqlUtils.getSqlSession();
        CourseMapper courseMapper = sqlSession.getMapper(CourseMapper.class);
        Course course = courseMapper.findCourseById(id);
        sqlSession.close();
        return course;
    }

    @Override
    public List<Course> findAll() {
        SqlSession sqlSession = MysqlUtils.getSqlSession();
        CourseMapper courseMapper = sqlSession.getMapper(CourseMapper.class);
        List<Course> courseList = courseMapper.findAll();
        sqlSession.close();
        return courseList;
    }
}
